package com.ycode.bang.anbang.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ycode.bang.anbang.MyApp;
import com.ycode.bang.anbang.R;
import com.ycode.bang.anbang.baseui.BaseActivity;
import com.ycode.bang.anbang.customview.MyGridView;
import com.ycode.bang.anbang.merchantactivity.LocalImageActivity;
import com.ycode.bang.anbang.model.OrderDetil;
import com.ycode.bang.anbang.network.FinalHttpService;
import com.ycode.bang.anbang.network.FinalHttpUtil;
import com.ycode.bang.anbang.network.servicelistener.WithJsonListener;
import com.ycode.bang.anbang.utils.CommonViewHolder;
import com.ycode.bang.anbang.utils.DialogProgress;
import com.ycode.bang.anbang.utils.DialogWithDelete2;
import com.ycode.bang.anbang.utils.RequestMapDev;
import com.ycode.bang.anbang.utils.SaveImage;
import com.ycode.bang.anbang.utils.SetImage;
import com.ycode.bang.anbang.utils.TAkePhotos;
import com.ycode.bang.anbang.utils.ToastUtil;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 转报修原因
 */
public class AddRecordActivity extends BaseActivity implements View.OnClickListener {
    @InjectView(R.id.edit_all)
    EditText mEdit;
    @InjectView(R.id.btn_againdeal)
    Button mBtnAd;
    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.recommendGridView)
    MyGridView recommendGridView;
    public static final int INFORMATION = 20169;
    private Uri sCurrentUri;//拍照时用于存放图片Uri
    private Dialog dialog;
    private ImagesAdapter imagesAdapter;
    private static final String FRIEND_CIRCLE_ADD_PICTURE = "friend_circle_and_picture";
    public static final int REQUEST_PICTURE_CODE = 22231;
    public static final int PHOTO_REQUEST_CAMERA = 22232;// 拍照
    private int imagelistsize = 0;//图片列表长度
    private ArrayList<String> sendtoserverimagelist = new ArrayList<String>();
    private ArrayList<String> pathModel = new ArrayList<String>();

    private int tag;
    private OrderDetil orderDetil = new OrderDetil();
    private String idKey = "1";//把这个订单的id设置成key值，根据这个key拿本地数据，有说明有缓存，没有就说明没有
    private String INTERFACE_PATH = "";//接口路径

    private ArrayList<String> upLoadList = new ArrayList<String>();
    DialogProgress mDialogProgress = new DialogProgress(this);
    private ArrayList<String> idList = new ArrayList<>();
    private String ids = "";
    private int orderId;
    private int assignmentRecordId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_record);
        ButterKnife.inject(this);
        if (this.getIntent().getExtras() != null) {
            Bundle bundle = this.getIntent().getExtras();
            tag = bundle.getInt("tag");
            orderId = bundle.getInt("orderId");
            assignmentRecordId = bundle.getInt("assignmentRecordId");
            idKey = orderDetil.getId() + "";
        }
        getInterface();
        initView();
        getData();
    }

    public void initView() {
        title.setText("添加记录");
        mBtnAd.setOnClickListener(this);


        //图片适配器
        if (null != pathModel && null != pathModel) {
            imagelistsize = pathModel.size();
        } else {
            imagelistsize = 0;
        }


        if (pathModel != null && pathModel.size() < 4) {
            pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
        }
        imagesAdapter = new ImagesAdapter(pathModel);
        recommendGridView.setAdapter(imagesAdapter);
    }

    public void getInterface() {
        if (tag == 1) {
            INTERFACE_PATH = RequestMapDev.SaveRecord;
        } else if (tag == 2) {
            INTERFACE_PATH = RequestMapDev.SaveRecord2;
        } else if (tag == 3) {
            INTERFACE_PATH = RequestMapDev.SaveRecord3;
        }
    }

    @Override
    protected void getSuccessRequest(Object response, int flag) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_againdeal:
                if (TextUtils.isEmpty(mEdit.getText().toString().trim())) {
                    ToastUtil.show(this, "请输入记录内容");
                    return;
                }
//                else if (pathModel.size() == 1 && pathModel.get(0).contains(FRIEND_CIRCLE_ADD_PICTURE)) {
//                    ToastUtil.show(this, "请上传图片");
//                    return;
//                }
                for (String s : pathModel) {
                    if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                        pathModel.remove(s);
                        break;
                    }
                }
                if (pathModel.size() == 0) {
                    addRecord();
                } else {
                    chuli(pathModel);
                }
//                DialogWithDelete2.showSimpleDialog(this);
//                setData();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //拍照

                case PHOTO_REQUEST_CAMERA:
                    if (hasSdcard()) {
                        Log.e("拍照相片路径", sCurrentUri + "");

                        if (data == null) {
                            String path = sCurrentUri + "";

                            final String cutpath = path.substring(7, path.length());
                            String afterpath = new SaveImage().compressed(cutpath);

                            if (afterpath != null) {
                                Log.e("", afterpath);


                                //先将带“添加符号”的图片删除，然后添加拍照的图片，
                                //最后判断总长度是否为8，若为8，就不操作，否则，添加带“添加符号”的图片

                                for (String s : pathModel) {
                                    if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                                        pathModel.remove(s);
                                        break;
                                    }
                                }
                                pathModel.add("file://" + afterpath);
                                if (pathModel.size() < 4) {
                                    pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
                                }

                                sendtoserverimagelist.add("file://" + afterpath);//用于存放上传服务器的图片列表

                                imagelistsize++;//用于显示的图片列表长度加1

                                imagesAdapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        Toast.makeText(AddRecordActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                    }
                    break;

                //选择照片

                case REQUEST_PICTURE_CODE:
                    requestPicture(data);
                    break;
            }
        }
    }

    /**
     * 图片的适配器
     *
     * @param
     * @param
     * @return
     */

    private class ImagesAdapter extends ArrayAdapter<String> {

        private List<String> list;

        public ImagesAdapter(List<String> list) {
            super(AddRecordActivity.this, 0, list);
            this.list = list;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_item_image, null);
            }

            ImageView delete = CommonViewHolder.get(convertView, R.id.delete);
            ImageView imageView = CommonViewHolder.get(convertView, R.id.image_show);
            TextView text = CommonViewHolder.get(convertView, R.id.image_text);
            final String uri = getItem(position);

            //根据是否是“添加图片”显示布局


            if (TextUtils.equals(uri, FRIEND_CIRCLE_ADD_PICTURE)) {
                ImageLoader.getInstance().displayImage("drawable://" + R.mipmap.ic_friend_circle_add_picture2, imageView);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                //imageView.setImageResource(R.mipmap.ic_friend_circle_add_picture);
                delete.setVisibility(View.GONE);
                text.setVisibility(View.GONE);
            } else {
                //ImageLoader.getInstance().displayImage(getItem(position), imageView);
                SetImage.setimage(AddRecordActivity.this, getItem(position), imageView);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                delete.setVisibility(View.VISIBLE);
                text.setVisibility(View.VISIBLE);
            }

            //删除时判断list长度是否小于8，若小于 则直接删除，不用添加“添加符号的图片” ，
            // 否则，先删除选中图片，然后判断原来有没有那张“添加图片”，若有 那就不操作，若无，就添加“添加图片”
            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //删除来自网络图片（编辑状态）

//                    if (netImages != null && netImages.images.size() > 0) {
//                        for (ProductsAndMaterial.Photo s : netImages.images) {
//                            if ((RequestMapDev.BASE_URL.substring(0, RequestMapDev.BASE_URL.length() - 1) + s.url).equals(list.get(position))) {
//                                //FinalHttpWu.deletephoto(ReleaseActivity.this, s.id);
//                                netImages.images.remove(s);
//                                isbianji = true;//此时已经修改过进入界面的信息，（用于退出时判断是否弹dialog）
//                                break;
//                            }
//                        }
//                    }


                    //删除用于上传服务器的图片

                    for (String s : sendtoserverimagelist) {
                        if (s.equals(list.get(position))) {
                            sendtoserverimagelist.remove(s);
                            break;
                        }
                    }


                    if (list.size() < 4) {
                        list.remove(position);

                    } else {
                        list.remove(position);
                        int i = 0;
                        for (String s : list) {
                            if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                                break;
                            } else {
                                i++;
                                if (i == list.size()) {
                                    list.add(FRIEND_CIRCLE_ADD_PICTURE);
                                }
                            }
                        }
                    }


                    imagelistsize--;//用于显示的列表长度减1

                    imagesAdapter.notifyDataSetChanged();
                }
            });

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (TextUtils.equals(uri, FRIEND_CIRCLE_ADD_PICTURE)) {
                        showbgdialog();
                    } else {
                        //查看大图
                    }
                }
            });

            return convertView;
        }
    }

    public void showbgdialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_select_image, null);
        TextView takephoto = (TextView) view.findViewById(R.id.tv_teke_picture);
        TextView select = (TextView) view.findViewById(R.id.tv_select_photo);
        TextView no = (TextView) view.findViewById(R.id.tv_sendContentDialogFragment_cancel);

        final AlertDialog.Builder builder =
                new AlertDialog.Builder(AddRecordActivity.this, android.R.style.Theme_Holo_Light_Dialog);
        dialog = builder.create();

        dialog.getWindow().setBackgroundDrawableResource(R.drawable.transparent_bg);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.mystyle);
        dialog.setCanceledOnTouchOutside(true);

        takephoto.setAlpha(0.85f);
        select.setAlpha(0.85f);
        no.setAlpha(0.85f);

        dialog.show();

//        WindowManager windowManager = context.getWindowManager();
//        Display display = windowManager.getDefaultDisplay();
//        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//        lp.width = (int) (display.getWidth()); //设置宽度
        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) ((dm.widthPixels) / 1.05);

        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);

        //拍照
        takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TAkePhotos(AddRecordActivity.this).cameraphoto(PHOTO_REQUEST_CAMERA);
                dialog.dismiss();
            }
        });
        //相册
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent localPicture = new Intent(AddRecordActivity.this, LocalImageActivity.class);
                localPicture.putExtra("listsize", imagelistsize);
                startActivityForResult(localPicture, REQUEST_PICTURE_CODE);
                dialog.dismiss();
            }
        });
        //取消
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 获取图片
     *
     * @param data Intent
     */
    private void requestPicture(Intent data) {
        pathModel.remove(FRIEND_CIRCLE_ADD_PICTURE);
        if (data != null) {
            pathModel.addAll(data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS));


            imagelistsize = imagelistsize + (data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS)).size();

            //用于存放上传服务器的图片列表
            sendtoserverimagelist.addAll(data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS));

        }
        if (pathModel.size() < 4) {
            pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
        }


        imagesAdapter.notifyDataSetChanged();
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public void setUri(Uri uri) {
        sCurrentUri = uri;
    }

    /**
     * 缓冲数据到本地
     */

    public void setData() {
        SharedPreferences.Editor edit = getSharedPreferences("huancun", MODE_PRIVATE).edit();
        edit.putString(idKey, mEdit.getText().toString());
        if (pathModel.size() > 1 && pathModel.size() != 4) {
            for (String s : pathModel) {
                if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                    pathModel.remove(s);
                    break;
                }
            }
            if (pathModel.size() > 1) {
                edit.putInt("size", pathModel.size()); /*sKey is an array*/
                for (int i = 0; i < pathModel.size(); i++) {
                    edit.remove("size" + i);
                    edit.putString("size" + i, pathModel.get(i));
                }
            } else {
                edit.putInt("size", 0); /*sKey is an array*/
            }
        }
        edit.commit();
    }

    public void getData() {
        SharedPreferences mPreference = getSharedPreferences("huancun", MODE_PRIVATE);
        SharedPreferences.Editor edit = getSharedPreferences("huancun", MODE_PRIVATE).edit();
        if (!TextUtils.isEmpty(mPreference.getString(idKey, ""))) {
            mEdit.setText(mPreference.getString(idKey, ""));
        }
        int size = mPreference.getInt("size", 0);
        if (size != 0) {
            pathModel.clear();
            for (int i = 0; i < size; i++) {
                pathModel.add(mPreference.getString("size" + i, null));
            }
            if (pathModel.size() != 4) {
                pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
            }
        }
        imagesAdapter.notifyDataSetChanged();
        edit.clear();
        edit.commit();
    }

    public void chuli(final List<String> urls) {
        mDialogProgress.showlistviewdialog("上传图片中……");
        upLoadList.clear();
        for (int i = 0; i < urls.size(); i++) {
            String filepath = TextUtils.substring(urls.get(i), 7, urls.get(i).length());
            try {
                upLoadList.add(SaveImage.compressed(filepath));
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(AddRecordActivity.this, "图片处理错误", Toast.LENGTH_SHORT).show();
            }
        }
        for (int i = 0; i < upLoadList.size(); i++) {
            uploadImage(upLoadList.get(i));
//            uploadImage(upLoadList.get(i).substring(8,upLoadList.get(i).length()));
        }
    }

    /**
     * 上传图片
     *
     * @param path
     */
    private void uploadImage(final String path) {
        FinalHttpService.upLoadImage(path, new WithJsonListener() {
            @Override
            public void onSuccess(String code, String msg, String data) {
//                ToastUtil.show(AddRecordActivity.this, msg);
                ToastUtil.logE("HandlePhotoActivity.this", "上传成功，结果:" + msg);
                Gson gson = new Gson();
                ArrayList<String> idList2 = new ArrayList<>();
                idList2 = (gson.fromJson(data, new TypeToken<List<String>>() {
                }.getType()));
                idList.addAll(idList2);
                if (idList.size() == upLoadList.size()) {
                    for (int i = 0; i < idList.size(); i++) {
                        if (i == idList.size() - 1) {
                            ids = ids + idList.get(i);
                        } else {
                            ids = ids + idList.get(i) + ";";
                        }

                    }
                    mDialogProgress.closedialog();
                    addRecord();
                }
            }

            @Override
            public void onError(String code, String msg) {
                ToastUtil.show(AddRecordActivity.this, "上传失败" + msg);
                if (tag == 1) {
                    DialogWithDelete2.showSimpleDialog(AddRecordActivity.this);
                    setData();
                }
                mDialogProgress.closedialog();
            }

            @Override
            public void onCookieError(String code, String msg) {
            }
        });
    }

    /**
     * 添加记录
     */
    private void addRecord() {
        AjaxParams mAjaxParam = new AjaxParams();
        mAjaxParam.put("csrfToken", MyApp.instance.getToken());
        mAjaxParam.put("assignmentRecordId", assignmentRecordId + "");
        mAjaxParam.put("recordContent", mEdit.getText().toString().trim());
        mAjaxParam.put("picture", ids);
        mAjaxParam.put("orderId", orderId + "");
        mDialogProgress.showlistviewdialog("添加记录中……");
        FinalHttpUtil.post(INTERFACE_PATH, mAjaxParam, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                mDialogProgress.closedialog();
                //放置数据
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("message");
                    String data = jsonObject.getString("data");
                    if (status.equals("0")) {
                        Log.e("这个接口是成功的", o);
                        Gson gson = new Gson();
                        finish();
                    } else {
                        ToastUtil.show(AddRecordActivity.this, msg.toString());
                    }
                } catch (Exception e) {
                    ToastUtil.show(AddRecordActivity.this, e.toString());
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                loginout_550(errorNo);
                mDialogProgress.closedialog();
                if (tag == 1) {
                    DialogWithDelete2.showSimpleDialog(AddRecordActivity.this);
                    setData();
                }
//                ToastUtil.show(AddRecordActivity.this, strMsg);

            }
        });
    }
}
